package cn.kkcxy.blog.server.controller;

import cn.kkcxy.blog.common.utils.MessageUtil;
import cn.kkcxy.blog.common.utils.SHA1;
import cn.kkcxy.blog.system.factory.wechat.WechatMessageFactory;
import cn.kkcxy.blog.system.factory.wechat.WechatMessageHandler;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Hidden
@RestController
public class CallBackController {

    private static final String token = "kkcxy";

    @Resource
    private WechatMessageFactory wechatMessageFactory;

    @GetMapping("/callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("wx验签, signature: {}, timestamp: {}, nonce: {}, echostr: {}", signature, timestamp, nonce, echostr);
        String sha1 = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(sha1)) {
            return echostr;
        }
        return "fail";
    }

    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
//        log.info("接收到来自于微信的请求, requestBody: {}, signature: {}, timestamp: {}, nonce: {}, msg_signature: {}", requestBody, signature, timestamp, nonce, msgSignature);
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);

        String msgType = msgMap.get("MsgType");
        String event = msgMap.get("Event");

        String messageTypeKey = event == null ? msgMap.get("MsgType") : StringUtils.join(msgType, ".", event);
        WechatMessageHandler handler = wechatMessageFactory.getHandlerByMessageType(messageTypeKey);
        if (Objects.isNull(handler)) {
            return HttpStatus.NOT_FOUND.getReasonPhrase();
        }
        return handler.dealMsg(msgMap);
    }
}
